package com.duo.utils;

import cn.hutool.core.util.IdUtil;
import com.duo.constant.GlobalConstant;
import io.jsonwebtoken.*;

import java.util.Date;

public class JwtUtil {

    /**
     * 获取JWT字符串
     * @param token
     * @return
     */
    public static String getJwt(String token){
        return Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                .claim("token", token)
                .setExpiration(new Date(System.currentTimeMillis() +  GlobalConstant.TIME))
                .setId(IdUtil.simpleUUID())
                .signWith(SignatureAlgorithm.HS256, GlobalConstant.SIGNATURE)
                .compact();
    }

    /**
     * 判断JWT是否在有效期内
     * @param jwtToken
     * @return
     */
    public static boolean isExpiration(String jwtToken){
        if (jwtToken == null){
            return false;
        }
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = null;

        try {
            claimsJws = parser.setSigningKey(GlobalConstant.SIGNATURE).parseClaimsJws(jwtToken);
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {
            return false;
        }

        Claims claims = claimsJws.getBody();
        return claims.getExpiration().after(new Date(System.currentTimeMillis()));
    }

    /**
     * 获取JWT内存放的token
     * @param jwtToken
     * @return
     */
    public static String getToken(String jwtToken){
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(GlobalConstant.SIGNATURE).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return claims.get("token").toString();
    }

}
